<template>
  <div class="main">
    <!--位置搜索 -->
    <div class="addression">
      <div class="addression-box">
        <div class="ar-warp">
          <i class="iconfont ar-back" @click="arback">&#xe618;</i>
          <div class="ar-title">选择地址</div>
          <input type="text" class="ar-input" placeholder="请输入地址" v-model="msg">
        </div>
        <div class="ar-box"></div>
        <section>
          <div class="ar-msg" :key='index' v-for="(item,index)  in armsg">
            <p>
              <span class="ar-msg-name">{{item.name}}</span>
            </p>
            <p class="ar-msg-position">{{item.address}}</p>
          </div>
        </section>
      </div>
    </div>
    <!--主页面  -->
    <div class="index-box">
      <div id="header">
        <div class="top">
          <div class="header_l" @click="arClick">
            <i class="iconfont">&#xe610;</i>
            <p>{{address.address ? address.address :''}}</p>
            <i class="iconfont jt">&#xe604;</i>
          </div>
          <div class="header_r">
            <div class="text">
              <span>{{weathermsg.temperature}}</span>
              <span>{{weathermsg.description}}</span>
            </div>
            <img :src="weathermsg.image_hash ? '//fuss10.elemecdn.com/'+weathermsg.image_hash.substr(0,1)+'/'+ weathermsg.image_hash.substr(1,2)+'/'+weathermsg.image_hash.substr(3)+'.png?imageMogr/format/webp/thumbnail/!69x69r/gravity/Center/crop/69x69//' : ''" class="weatherimg" alt="天气图标" />
          </div>
        </div>
        <div class="search">
          <router-link to="/search">
            <input type="text" placeholder="搜索商家、商品" />
          </router-link>
        </div>
        <div class="food">
          <span :key="index" v-for="(item, index) in hot_search">{{item.word}}</span>
        </div>
      </div>
      <div id="hotsearch">
        <div class="swiper-container">
          <div class="swiper-wrapper">
            <div class="swiper-slide">
              <a href="#" :key="index" v-for="(item, index) in nearby" v-if="index < 8">
                <img :src="item.image_hash ? '//fuss10.elemecdn.com/'+ item.image_hash.substr(0,1) + '/' + item.image_hash.substr(1,2) + '/'
                              + item.image_hash.substr(3) + (item.image_hash.slice(-3) == 'png' ? '.png' : '.jpeg') +'?imageMogr/format/webp/thumbnail/!90x90r/gravity/Center/crop/90x90/':''" alt=".." />
                <span>{{item.name}}</span>
              </a>
            </div>
            <div class="swiper-slide">
              <a href="#" :key="index" v-for="(item, index) in nearby" v-if="index > 7 && index < 16">
                <img :src="item.image_hash ?'//fuss10.elemecdn.com/'+ item.image_hash.substr(0,1) + '/' + item.image_hash.substr(1,2) + '/'
                              + item.image_hash.substr(3) + (item.image_hash.slice(-3) == 'png' ? '.png' : '.jpeg') +'?imageMogr/format/webp/thumbnail/!90x90r/gravity/Center/crop/90x90/' : ''" alt=".." />
                <span>{{item.name}}</span>
              </a>
            </div>
          </div>
          <div class="swiper-pagination"></div>
        </div>
      </div>
      <h1>推荐商家</h1>
      <div id="recommend">
        <ul>
          <li :key="index" v-for="(item, index) in seller">
            <router-link :to="'/detail/' + item.id">
              <img class="logo" :src="item.image_path ?'//fuss10.elemecdn.com/' + item.image_path.substr(0,1) + '/' + item.image_path.substr(1,2) + '/'
              + item.image_path.substr(3) + (item.image_path.slice(-3) == 'png' ? '.png' : '.jpeg') + '?imageMogr/format/webp/thumbnail/!120x120r/gravity/Center/crop/120x120/':''" alt=".." />
              <div class="right">
                <h5>
                  <span class="brand" v-if="item.is_premium">品牌</span>{{item.name}}</h5>
                <div class="sale">
                  <img class="star" src="../assets/star.png" alt=".." />
                  <span>月售{{item.recent_order_num}}单</span>
                  <span class="bee" v-if="item.delivery_mode">蜂鸟专送</span>
                </div>
                <p>
                  <span>￥{{item.float_minimum_order_amount?item.float_minimum_order_amount.toFixed(1):''}}起送/&nbsp;</span>
                  <span>{{item.piecewise_agent_fee?item.piecewise_agent_fee.description:''}}/&nbsp;</span>
                  <span>{{item.average_cost}}</span>
                  <span class="time">{{item.order_lead_time}}分钟</span>
                  <span class="info">{{item.distance > 1000 ? (item.distance / 1000).toFixed(2) + 'km' : item.distance + 'm'}}&nbsp;/&nbsp;</span>
                </p>
              </div>
              <div class="bottom">
                <div class="activity" :key="i" v-for="(val, i) in item.activities" v-if="i > 1 ? isShow[index] : true">
                    <span class="new" :style="'background: #' + val.icon_color">{{val.icon_name}}</span>
                    <span class="tips">{{val.tips}}</span>
                    <span @click.prevent="showHide(index)" class="show" v-if="i == 0 && item.activities.length >2">
                      {{item.activities.length}}个活动
                      <i class="iconfont">&#xe604;</i>
                    </span>
                </div>
              </div>
            </router-link>
          </li>
        </ul>
      </div>
      <Footerpage></Footerpage>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import axios from 'axios'
import Swiper from 'swiper'
import $ from 'jquery'
import '../assets/css/swiper-3.4.2.min.css'
import Router from 'vue-router'
import Footerpage from './Footer'
export default {
  name: 'main',
  components: {
    Footerpage
  },
  data() {
    return {
      hot_search: [],
      nearby: [],
      timeer: null,
      isShow: [],
      msg: '',
      limit: 10
    }
  },
  methods: {
    showHide(index) {
      // 点击活动隐现：
      Vue.set(this.isShow, index, !this.isShow[index])
    },
    arClick() {
      //首页定位点击跳转搜索位置页面
      $('.addression').css('transform', 'translateX(0)')
      $('.index-box').animate({
        'display': 'none'
      })
    },
    arback() {
      //搜索位置页面，点击返回
      $('.addression').css('transform', 'translateX(755px)')
      $('.index-box').show()
    }
  },
  watch: {
    //监听搜索位置页面，输入框输入值
    msg: function (newVal, oldVal) {
      var oSelf = this;
      //延时1s进行请求操作
      clearTimeout(oSelf.timeer)
      oSelf.timeer = setTimeout(function () {
        axios.get('http://localhost:3000/address', {
          params: {
            keyword: encodeURIComponent(newVal),
            latitude: oSelf.$store.state.str[0].latitude,
            longitude: oSelf.$store.state.str[0].longitude
          }
        }).then(function (res) {
          var data = res.data
          oSelf.$store.commit('AR', data)
        }).catch(function (err) {
          console.log('搜索位置失败')
        })
      }, 1000);

    }
  },
  computed: {
    address() {
      //返回定位信息
      return this.$store.state.str
    },
    weathermsg() {
      //返回天气信息
      return this.$store.state.wt
    },
    armsg() {
      //返回搜索定位结果
      return this.$store.state.ar
    },
    seller() {
      return this.$store.state.seller
    }
  },
  mounted() {
    var oSelf = this
    if (sessionStorage.getItem('address')) {
      var str = JSON.parse(sessionStorage.getItem('address'))
      oSelf.$store.commit('DW', str)
      // //天气信息请求DW
      var lat = str.latitude
      var lon = str.longitude
      getAllmsg(lat, lon)
      return
    } else {
      var oSelf = this
      var map, geolocation;
      //加载地图，调用浏览器定位服务
      map = new AMap.Map('container');
      map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：无穷大
          buttonPosition: 'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
      });
      //解析定位结果
      function onComplete(data) {
        var str = {};
        str = { 'longitude': data.position.getLng(), 'latitude': data.position.getLat(), 'address': data.addressComponent.district + data.addressComponent.township + data.addressComponent.street + data.addressComponent.streetNumber }

        //保存到sessionStorage
        sessionStorage.setItem('address', JSON.stringify(str))
        //提交一个裂变
        oSelf.$store.commit('DW', str)
        // //天气信息请求DW
        var lat = str.latitude
        var lon = str.longitude
        getAllmsg(lat, lon)
      }
      //解析定位错误信息
      function onError(data) {
        console.log('定位失败')
      }
    }
    function getAllmsg(lat, lon) {

      //发起天气信息请求
      axios.get('http://localhost:3000/weather', {
        params: {
          latitude: lat,
          longitude: lon
        }
      }).then(function (res) {
        var data = res.data
        oSelf.$store.commit('WEATHER', data)
      }).catch(function (err) {
        console.log('定位失败')
      })
      //请求热搜
      axios.get('http://localhost:3000/hot_search', {
        params: {
          latitude: lat,
          longitude: lon
        }
      }).then(function (res) {
        oSelf.$store.commit('SELLERMSG', res.data)
        oSelf.hot_search = res.data
      }).catch(function (err) {
        console.log(err)
      })
      //请求附近美食
      axios.get('http://localhost:3000/nearby', {
        params: {
          latitude: lat,
          longitude: lon
        }
      }).then(function (res) {
        oSelf.nearby = res.data[0].entries
        new Swiper('.swiper-container', {
          autoplay: 3000,
          pagination: '.swiper-pagination'
        })
      }).catch(function (err) {
        console.log(err)
      })
      //请求商家
      function reqSeller(lat, lon) {
        axios.get('http://localhost:3000/seller', {
          params: {
            latitude: lat,
            longitude: lon,
            limit: oSelf.limit
          }
        }).then(function (res) {
          var arr = []
          for (var i = 0; i < res.data.length; i++) {
            arr.push(false)
          }
          oSelf.isShow = arr
          oSelf.$store.commit('SELLERMSG', res.data)
        }).catch(function (err) {
          console.log(err)
        })
      }
      reqSeller(lat, lon);
      $(window).scroll(function () {	//下拉加载
        if ($(this).scrollTop() + $(this).height() == $(document).height()) {
          oSelf.limit += 5
          reqSeller(lat, lon);
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang='scss'>
@import '../../static/px2rem.scss';
.addression {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10000;
  overflow: auto;
  background-color: #f4f4f4;
  transform: translateX(755px);
  transition: all ease 0.3s;
  .ar-warp {
    position: fixed;
    width: 100%;
    background-image: linear-gradient(90deg, #0af, #0085ff);
    color: #fff;
    text-align: center;
    font-size: px2rem(12);
    padding-bottom: px2rem(12);
    .ar-back {
      display: block;
      width: px2rem(20);
      height: px2rem(20);
      color: #fff;
      position: absolute;
      left: px2rem(12);
      top: px2rem(12);
      font-size: px2rem(18)
    }
    .ar-title {
      line-height: px2rem(43);
      font-size: px2rem(18)
    }
    .ar-input {
      border: none;
      outline: none;
      width: 90%;
      margin-top: px2rem(5);
      height: px2rem(27);
      border-radius: px2rem(27);
      padding: 0 px2rem(18);
      font-size: px2rem(13);
      line-height: px2rem(20)
    }
  }
  .ar-box {
    height: px2rem(88);
  }
  .ar-msg {
    font-size: px2rem(12);
    background-color: #fff;
    padding: px2rem(15) px2rem(10);
    .ar-msg-name {
      font-weight: 700;
      font-size: px2rem(14);
    }
    .ar-msg-position {
      color: #999;
      font-size: px2rem(12);
      margin-top: px2rem(2);
    }
  }
}

.main {
  width: 100%;
  #header {
    height: px2rem(122);
    width: 100%;
    background: #009dfe;
    display: flex;
    flex-direction: column;
    align-items: center;
    .top {
      width: 92%;
      height: px2rem(35);
      margin-top: px2rem(10);
      display: flex;
      justify-content: space-between;
      align-items: center;
      .header_l {
        height: px2rem(21);
        width: 60%;
        p {
          font-size: px2rem(17);
          color: white;
          float: left;
          max-width: 80%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .jt {
          float: right;
          font-size: px2rem(17)
        }
        i {
          font-size: px2rem(18);
          float: left;
          margin-right: px2rem(3);
          color: white;
        }
      }
      .header_r {
        .text {
          display: flex;
          flex-direction: column;
          justify-content: center;
          float: left;
          color: white;
          font-size: px2rem(13);
          text-align: right;
        }
        .weatherimg {
          margin-left: px2rem(4);
          width: px2rem(27);
          height: px2rem(27);
          max-width: 100%;
        }
        i {
          font-size: px2rem(24);
          color: white;
          float: right;
          margin: px2rem(5) 0 0 px2rem(2);
        }
      }
    }
    .search {
      width: 100%;
      margin: px2rem(7) 0 0;
      input {
        width: 92%;
        margin: 0 auto;
        height: px2rem(35);
        display: block;
        border-radius: px2rem(16);
        border: 0;
        padding-left: 35%;
        font-size: px2rem(12);
      }
    }
    .food {
      width: 92%;
      height: px2rem(28);
      line-height: px2rem(28);
      white-space: nowrap;
      overflow-x: auto;
      span {
        color: white;
        font-size: px2rem(12);
        margin-right: px2rem(13);
      }
    }
  }
  #hotsearch {
    height: px2rem(177);
    width: 100%;
    .swiper-container {
      height: 100%;
      width: 100%;
      a {
        height: px2rem(64);
        width: 25%;
        padding-top: px2rem(11);
        display: flex;
        flex-direction: column;
        align-items: center;
        float: left;
        img {
          width: px2rem(45);
          height: px2rem(45);
        }
        span {
          line-height: px2rem(20);
          font-size: px2rem(12);
          color: #666;
        }
      }
    }
  }
  h1 {
    height: px2rem(44);
    line-height: px2rem(30);
    border-top: px2rem(10.5) solid #f5f5f5;
    border-bottom: px2rem(0.5) solid #f5f5f5;
    padding-left: px2rem(15);
    font-size: px2rem(15);
  }

  #recommend {
    width: 100%;
    ul {
      width: 100%;
      li {
        float: left;
        padding: px2rem(15) 0;
        width: 100%;
        border-bottom: px2rem(0.5) solid #f7f7f9;
        .logo {
          width: px2rem(60);
          height: px2rem(60);
          margin: 0 px2rem(10);
          float: left;
        }
        .right {
          width: 75%;
          float: left;
          color: #666;
          h5 {
            font-size: px2rem(15);
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            line-height: px2rem(15);
            color: black;
            .brand {
              display: inline-block;
              padding: 0 px2rem(2.5);
              margin-right: px2rem(5);
              border-radius: px2rem(3);
              background-color: #ffd930;
              color: #52250a;
              font-weight: 700;
              font-size: px2rem(11);
            }
          }
          .sale {
            height: px2rem(13);
            line-height: px2rem(13);
            margin: px2rem(5) 0;
            .star {
              width: px2rem(70);
              height: px2rem(9);
              display: inline;
            }
            span {
              font-size: px2rem(11);
            }
            .bee {
              background: #2395ff;
              color: white;
              border-radius: px2rem(1);
              float: right;
              padding: px2rem(1);
            }
          }
          p {
            margin-top: px2rem(7);
            height: px2rem(15);
            span {
              float: left;
              font-size: px2rem(11);
            }
            .info {
              float: right;
            }
            .time {
              float: right;
              color: #009dfe;
            }
          }
        }
        .bottom {
          float: left;
          width: 75%;
          position: relative;
          margin-top: px2rem(7.5);
          border-top: px2rem(0.5) solid #eee;
          color: #939393;
          font-size: px2rem(10);
          .activity {
            margin: px2rem(9) 0;
            .new {
              color: white;
              border-radius: px2rem(3);
              font-size: px2rem(10);
              padding: px2rem(1);
            }
            .tips {
              display: inline-block;
              width: 71%;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
            .show {
              float: right;
              i {
                font-size: px2rem(12);
              }
            }
          }
        }
      }
    }
  }
}
</style>
